import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select,Tooltip, Radio, Switch, TreeSelect, message } from 'antd';
import { formatMessage,FormattedMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import {InfoCircleOutlined} from "@ant-design/icons";
import React, { useState, useEffect } from 'react';
import styles from '../style.less';

import CryptoJS from 'crypto-js';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';
import DataLang from './DataLang';
import { arrayOf } from 'prop-types';
// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate, dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  const [picture2, setPicture2] = useState<any[]>([]);
  const [uploadChanged2, setUploadChanged2] = useState<boolean>(false);

  const [dataLangModalVisible, handleDataModalVisible] = useState<boolean>(false);
  const [fieldTitle, setFieldTitle] = useState<any>('');
  const [nameListLang, setnameList] = useState<any>(common?.multilingualoption);
  const [siteDescJson, setSiteDescJson] = useState<any>(dataFormValues?.descriptionArr || []);
  const [siteNameJson, setSiteNameJson] = useState<any>(dataFormValues?.nameArr || []);

  useEffect(()=>{
    console.log(dataFormValues?.nameArr);
    setSiteDescJson(dataFormValues?.descriptionArr || []);
    setSiteNameJson(dataFormValues?.nameArr || []);
  },[dataFormValues])

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (picture.length > 0) {
        fieldsValue.cover_file_id = picture[0].file_id
        fieldsValue.cover_file_url = picture[0].file_url
      }
      if (picture2.length > 0) {
        fieldsValue.banner_file_id = picture2[0].file_id
        fieldsValue.banner_file_url = picture2[0].file_url
      }
      // 如果是更新
      if (isUpdate) {
        fieldsValue.id = dataFormValues.id;
      }
      console.log("submit fields ", fieldsValue)
      let arr1 = [];
      siteNameJson.map(item =>{
        let obj = {
          key:item.key,
          lang_text:item.lang_text,
          lang_content:item.lang_content,
        };
        arr1.push(obj)
      })
      let arr2 = [];
      siteDescJson.map(item =>{
        let obj = {
          key:item.key,
          lang_text:item.lang_text,
          lang_content:item.lang_content,
        };
        arr2.push(obj)
      })
      fieldsValue.name_arr = JSON.stringify(arr1)
      fieldsValue.description_arr = JSON.stringify(arr2)
      fieldsValue.admin_members = fieldsValue.admin_members?.join(',');
      fieldsValue.publish_post_roles = fieldsValue.publish_post_roles?.join(',');
      // 如果更新成功之后，重置表单
      handleSubmit(fieldsValue).then((success: any) => {
        console.log('handleSubmit then success is ', success)
        if (success) {
          form.resetFields()
          setPicture([])
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList: any) => {
    setUploadChanged(true)
    if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
      message.error(fileList[0].response.message);
      return
    }
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if (fileArr.length > 0) {
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    } else if (fileArr.length === 0) {
      console.log('set picture []')
      setPicture([])
    }
  }
  const setUploadFile2 = (fileList: any) => {
    setUploadChanged2(true)
    if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
      message.error(fileList[0].response.message);
      return
    }
    const fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if (fileArr.length > 0) {
      setPicture2(fileArr)
      setPreviewImg(fileArr[0].file_url)
    } else if (fileArr.length === 0) {
      console.log('set picture []')
      setPicture2([])
    }
  }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues?.cover_file_url)
  const defaultPicture2 = DataHelper.buildFileByUrl(dataFormValues?.banner_file_url)
  
  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadButton2 = DataHelper.showUploadBtn(isUpdate, picture2, defaultPicture2, uploadChanged2)
  console.log(showUploadButton2);
  console.log(showUploadButton);
  // 表单提交
  const handleSubmitDataForm = (value: any, title: any) => {
    console.log(value, 241)
    setnameList(value)
    if (title == "name") {
      setSiteNameJson(value);
      console.log(2, 45)
    } else if (title == "desc") {
      setSiteDescJson(value);
      console.log(4, 56)
    }
    handleDataModalVisible(false)
  }

  const userInfo = localStorage.getItem('user-login-info');
  let fresnsClient = eval("(" + userInfo + ")");
  const timestamp = new Date().getTime().toString().substr(0,10);
  var md5String = `appId=${fresnsClient?.app_id}&platform=${fresnsClient?.platform}&timestamp=${timestamp}&key=${fresnsClient?.app_secret}`;

  // 弹出框
  // @ts-ignore
  return <Modal
    className={styles.input}
    destroyOnClose
    title={isUpdate ? '编辑' : '新建'}
    width={DataHelper.DEFAULT_MODAL_WIDTH}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='所属分类'>
      {form.getFieldDecorator('parent_id', {
        initialValue: isUpdate ? dataFormValues?.parent_id?.toString() : '',
        rules: [{ required: true, message: '请选择'}],
      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common?.oneGroupOption && TsxHelper.buildSelectOption(common?.oneGroupOption)}
      </Select>)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'显示顺序'}>
      {form.getFieldDecorator('rank_num', {
        initialValue: isUpdate ? dataFormValues.rank_num : 888,
        rules: [{ required: true, message: '请输入'}],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }} />)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'小组名称'}>
      {form.getFieldDecorator('name', {
        initialValue: siteNameJson.length > 0 ? siteNameJson[0].lang_content : '',
        rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input readOnly
        onClick={() => {
          setFieldTitle('name');
          // console.log(dataFormValues?.nameArr);
          // setSiteNameJson(isUpdate? dataFormValues?.nameArr : []);
          if (siteNameJson && siteNameJson.length > 0) {
            setnameList(siteNameJson);
          } else {
            setnameList(JSON.parse(JSON.stringify(common.multilingualoption)));
          }
          handleDataModalVisible(true);
        }}
      />)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'小组描述'}>
      {form.getFieldDecorator('desc', {
        initialValue: siteDescJson.length > 0 ? siteDescJson[0].lang_content : '',
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input readOnly
        onClick={() => {
          setFieldTitle('desc');
          // setSiteDescJson(isUpdate? dataFormValues?.descriptionArr : []);
          if (siteDescJson && siteDescJson.length > 0) {
            setnameList(siteDescJson);
          } else {
            setnameList(JSON.parse(JSON.stringify(common.multilingualoption)));
          }
          handleDataModalVisible(true);
        }}
      />)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'小组图标'}>
      {form.getFieldDecorator('picture', {
        // initialValue: defaultPicture,
        // rules: [{required: true, message: '请上传图片'}],
      })(
        <Upload
          listType={'picture'}
          className={'upload-list-inline'}
          action="/api/admin/tweetfiles/upload"
          defaultFileList={defaultPicture}
          beforeUpload={(file) => {
            console.log('before upload file type:', file.type)
            // todo: 这里可以对上传文件类型做限制
            return true;
          }}
          data={{ type: 'image' }}
          onRemove={() => setPicture([])}
          onChange={(changeObj) => setUploadFile(changeObj.fileList)}
          onPreview={() => handlePreviewModalVisible(true)}
          headers={{
            Authorization: `Bearer ${token}`,
            'platform': fresnsClient?.platform,
            'timestamp': timestamp,
            'appId': fresnsClient?.app_id,
            'sign':  CryptoJS.MD5(md5String).toString(),
          }}
        >
          {
            showUploadButton ? (
              <Button>
                <Icon type="upload" /> {formatMessage({ id: 'app.base.upload' })}
              </Button>
            ) : null
          }
        </Upload>
      )}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'小组条幅'}>
      {form.getFieldDecorator('picture2', {
        // initialValue: defaultPicture,
        // rules: [{required: true, message: '请上传图片'}],
      })(
        <Upload
          listType={'picture'}
          className={'upload-list-inline'}
          action="/api/admin/tweetfiles/upload"
          defaultFileList={defaultPicture2}
          beforeUpload={(file) => {
            console.log('before upload file type:', file.type)
            // todo: 这里可以对上传文件类型做限制
            return true;
          }}
          data={{ type: 'image' }}
          onRemove={() => setPicture2([])}
          onChange={(changeObj) => setUploadFile2(changeObj.fileList)}
          onPreview={() => handlePreviewModalVisible(true)}
          headers={{
            Authorization: `Bearer ${token}`,
            'platform': fresnsClient?.platform,
            'timestamp': timestamp,
            'appId': fresnsClient?.app_id,
            'sign':  CryptoJS.MD5(md5String).toString(),
          }}
        >
          {
            showUploadButton2 ? (
              <Button>
                <Icon type="upload" /> {formatMessage({ id: 'app.base.upload' })}
              </Button>
            ) : null
          }
        </Upload>
      )}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='小组模式'>
      {form.getFieldDecorator('type_mode', {
        initialValue: isUpdate ? dataFormValues.type_mode : '',
        rules: [{ required: true, message: '请选择'}],
      })(<Radio.Group buttonStyle="solid">
        <Radio value={1}>公开（任何人都能查看小组内帖子</Radio>
        <Radio value={2}>非公开（只有成员才能查看小组内帖子）</Radio>
        {/* {common.selectOption && TsxHelper.buildRadioOption(common.selectOption)} */}
      </Radio.Group>)}
    </FormItem>
    {
      form.getFieldValue('type_mode') == 2 &&
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='是否可发现'>
        {form.getFieldDecorator('timeFormatMinute', {
          initialValue: isUpdate ? dataFormValues?.timeFormatMinute : '',
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Radio.Group buttonStyle="solid">
          <Radio value={1}>可发现（任何人都能找到这个小组）</Radio>
          <Radio value={2}>不可发现（只有成员能找到这个小组）</Radio>
          {/* {common.selectOption && TsxHelper.buildRadioOption(common.selectOption)} */}
        </Radio.Group>)}
      </FormItem>
    }
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='关注方式'>
      {form.getFieldDecorator('type_follow', {
        initialValue: isUpdate ? dataFormValues.type_follow : '',
        rules: [{ required: true, message: '请选择'}],
      })(<Radio.Group buttonStyle="solid">
        {/* {common?.typeFollow && TsxHelper.buildRadioOption(common?.typeFollow)} */}
        <Radio value={1}>原生方式</Radio>
        <Radio value={2}>插件方式</Radio>
      </Radio.Group>)}
    </FormItem>
    {
      form.getFieldValue('type_follow') == 2 &&
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='关联插件'>
        {form.getFieldDecorator('plugin_unikey', {
          initialValue: isUpdate ? dataFormValues?.plugin_unikey?.toString() : '',
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
          {common?.plugOption && TsxHelper.buildSelectOption(common?.plugOption)}
        </Select>)}
      </FormItem>
    }
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='是否推荐'>
      {form.getFieldDecorator('is_recommend', {
        initialValue: isUpdate ? dataFormValues.is_recommend : '',
        rules: [{ required: true, message: '请选择'}],
      })(<Radio.Group buttonStyle="solid">
        {/* {common?.typeFollow && TsxHelper.buildRadioOption(common?.typeFollow)} */}
        <Radio value={1}>不推荐</Radio>
        <Radio value={2}>推荐</Radio>
      </Radio.Group>)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='小组管理员'>
      {form.getFieldDecorator('admin_members', {
        initialValue: isUpdate ? dataFormValues?.permission_decode?.admin_members : [],
        rules: [{ required: true, message: '请选择'}],
      })(<Select
      mode="multiple" allowClear  placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}
    >
        {common?.memberOption && TsxHelper.buildSelectOption(common?.memberOption)}
    </Select>)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='发布权限'>
      {form.getFieldDecorator('publish_post', {
        initialValue: isUpdate ? dataFormValues.publish_post : '',
      })(<Radio.Group buttonStyle="solid">
        {/* {common?.typeFollow && TsxHelper.buildRadioOption(common?.typeFollow)} */}
        <Radio value={1}>所有人</Radio>
        <Radio value={2}>仅关注了小组的成员</Radio>
        <Radio value={3}>仅指定的角色成员</Radio>
      </Radio.Group>)}
    </FormItem>
    {
      form.getFieldValue('publish_post') == 3 &&
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='有权发表的角色'>
      {form.getFieldDecorator('publish_post_roles', {
        initialValue: isUpdate ? dataFormValues?.permission_decode?.publish_post_roles : [],
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Select
      mode="multiple" allowClear  placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}
    >
        {common?.roleOption && TsxHelper.buildSelectOption(common?.roleOption)}
    </Select>)}
    </FormItem>
    }
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} 
    label={
      <span>
        <FormattedMessage id="need_to_review" />
        <em className={styles.optional}>
          <Tooltip title={<FormattedMessage id="小组管理员不受影响" />}>
            <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
          </Tooltip>
        </em>
      </span>
    }>
      {form.getFieldDecorator('publish_post_review', {
        initialValue: isUpdate ? dataFormValues?.publish_post_review : '',
        // rules: [{ required: true, message: '请选择！',}],
      })(<Radio.Group buttonStyle="solid">
          <Radio value={0}>不需要</Radio>
          <Radio value={1}>需要</Radio>
          {/* {common.selectOption && TsxHelper.buildRadioOption(common.selectOption)} */}
        </Radio.Group>
      )}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='评论权限'>
      {form.getFieldDecorator('publish_comment', {
        initialValue: isUpdate ? dataFormValues.publish_comment : '',
      })(<Radio.Group buttonStyle="solid">
        {/* {common?.typeFollow && TsxHelper.buildRadioOption(common?.typeFollow)} */}
        <Radio value={1}>所有人</Radio>
        <Radio value={2}>仅关注了小组的成员</Radio>
        <Radio value={3}>仅指定的角色成员</Radio>
      </Radio.Group>)}
    </FormItem>
    {
      form.getFieldValue('publish_comment') == 3 &&
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='有权发表的角色'>
      {form.getFieldDecorator('publish_comment_roles', {
        initialValue: isUpdate ? dataFormValues?.publish_comment_roles : [],
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Select
      mode="multiple" allowClear  placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}
    >
        {common?.roleOption && TsxHelper.buildSelectOption(common?.roleOption)}
    </Select>)}
    </FormItem>
    }
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} 
    label={
      <span>
        <FormattedMessage id="need_to_review" />
        <em className={styles.optional}>
          <Tooltip title={<FormattedMessage id="小组管理员不受影响" />}>
            <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
          </Tooltip>
        </em>
      </span>
    }>
      {form.getFieldDecorator('publish_comment_review', {
        initialValue: isUpdate ? dataFormValues?.publish_comment_review : '',
        // rules: [{ required: true, message: '请选择！',}],
      })(<Radio.Group buttonStyle="solid">
          <Radio value={0}>不需要</Radio>
          <Radio value={1}>需要</Radio>
          {/* {common.selectOption && TsxHelper.buildRadioOption(common.selectOption)} */}
        </Radio.Group>
      )}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label='启用状态'>
      {form.getFieldDecorator('is_enable', {
        initialValue: isUpdate ? dataFormValues.is_enable : '',
        rules: [{ required: true, message: '请选择！'}],
      })(<Radio.Group buttonStyle="solid">
        {/* {common?.typeFollow && TsxHelper.buildRadioOption(common?.typeFollow)} */}
        <Radio value={true}>启用</Radio>
        <Radio value={false}>不启用</Radio>
      </Radio.Group>)}
      </FormItem>
      <DataLang
        dataModalVisible={dataLangModalVisible}
        isUpdate={isUpdate}
        dataFormValues={dataFormValues}
        common={common || {}}
        // name={modalName}
        nameList={nameListLang}
        title={fieldTitle}
        onSubmit={handleSubmitDataForm}
        onCancel={() => handleDataModalVisible(false)}
      />
      {
        previewModelVisible && (
          <PreviewForm
            previewModelVisible={previewModelVisible}
            onVisibleModel={handlePreviewModalVisible}
            previewImg={previewImg}
          />
        )
      }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
